package com.yanq.liancar.activity;
/*
 *  @创建者     liyan
 *  @创建时间   2018/11/1  9:44
 *  @描述       ${TODO}
 */


import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.InfoWinAdapter;
import com.yanq.liancar.adapter.StaffListAdapter;
import com.yanq.liancar.bean.RescueOrderDetailsBean;
import com.yanq.liancar.bean.SelectStaffBean;
import com.yanq.liancar.bean.SelectStaffBean1;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RescueOrderDetailsActivity extends BaseToolbarActivity implements AMap.OnMarkerClickListener {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right2)
    ImageView ivRight2;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.common_toolbar)
    Toolbar commonToolbar;
    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.mapview)
    MapView mapview;
    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_carNum)
    TextView tvCarNum;
    @BindView(R.id.tv_phoneNum)
    TextView tvPhoneNum;
    @BindView(R.id.img_Call)
    ImageView imgCall;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.view2)
    View view2;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.view3)
    View view3;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.view4)
    View view4;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.tv_time1)
    TextView tvTime1;
    @BindView(R.id.tv_time2)
    TextView tvTime2;
    @BindView(R.id.tv_time3)
    TextView tvTime3;
    @BindView(R.id.tv_place)
    TextView tvPlace;
    @BindView(R.id.tv_reason)
    TextView tvReason;
    @BindView(R.id.tv_road)
    TextView tvRoad;
    @BindView(R.id.btn_complete)
    Button btnComplete;
    @BindView(R.id.ll_time)
    LinearLayout llTime;

    private AMap mAMap;
    //定义一个UiSettings对象
    private UiSettings mUiSettings;
    private Marker marker;
    private LatLng markerPosition, myLocation;
    private MyLocationStyle myLocationStyle;
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private double Latitude, Longitude;
    private int shopID, status,orderID;
    private String tel;
    private InfoWinAdapter mInfoWinAdapter;
    private StaffListAdapter mStaffListAdapter;
    private List<SelectStaffBean.DataBean> mBeanList=new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rescueorderdetails);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("急速救援订单详情");

        orderID = getIntent().getIntExtra("id", 0);
        shopID=getIntent().getIntExtra("shopID", 0);
        initOkGoWhole();

        mapview.onCreate(savedInstanceState);

        init();

        getLocation();

        mStaffListAdapter=new StaffListAdapter(R.layout.stafflist,mBeanList);

    }

    @OnClick({R.id.img_Call, R.id.btn_complete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_Call:
                Uri uri = Uri.parse("tel:" + tel);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
                break;
            case R.id.btn_complete:
                //指派订单
                if (status == 0) {
                    if (mBeanList.size()>1){
                        myDialog();
                    }else {
                        RxToast.info("暂无员工数据");
                    }
                }else if (status==1){       //确认到达
                    arriveDialog();
                }else if (status==2){
                    Bundle bundle=new Bundle();
                    bundle.putInt("shopID",shopID);
                    RxActivityTool.skipActivity(this, UploadRescuePictureActivity.class,bundle);
                }
                break;
        }
    }


    /**
     * 初始化AMap对象
     */

    private void init() {

        if (mAMap == null) {
            mAMap = mapview.getMap();
            mUiSettings = mAMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(true);  //显示缩放按钮
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
            mAMap.moveCamera(CameraUpdateFactory.zoomTo(12));
            mAMap.setOnMarkerClickListener(this);
            mInfoWinAdapter = new InfoWinAdapter();
            mAMap.setInfoWindowAdapter(mInfoWinAdapter);
        }

        // addGrowMarker();

    }

    /**
     * 添加带生长效果marker
     */

    private void addGrowMarker(LatLng latLng) {
        MarkerOptions options = new MarkerOptions();
        options.position(latLng);
        options.visible(true);
        options.title("救援地点");
        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon_openmap_mark)));
        options.setFlat(false);
        options.anchor(0.5f, 1.0f);
        marker = mAMap.addMarker(options);
        marker.showInfoWindow();
        //        Animation markerAnimation = new ScaleAnimation(0, 1, 0, 1); //初始化生长效果动画
        //
        //        markerAnimation.setDuration(1000);  //设置动画时间 单位毫秒
        //
        //        marker.setAnimation(markerAnimation);


    }

    private void getLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，并且蓝点会跟随设备移动。
        mAMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        mAMap.getUiSettings().setMyLocationButtonEnabled(true);  //设置默认定位按钮是否显示，非必需设置。
        mAMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。


        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        Latitude = aMapLocation.getLatitude();//获取纬度
                        Longitude = aMapLocation.getLongitude();//获取经度
                        LogUtils.e("经纬度====", Latitude + "=======" + Longitude);
                        myLocation = new LatLng(Latitude, Longitude);

                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }

    //全部
    private void initOkGoWhole() {
        OkGo.<String>post(Config.s + "llc/api/RoadRescueController/selectRescueOrderDetails")
                .tag(this)
                .params("id", orderID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        RescueOrderDetailsBean bean = gson.fromJson(response.body(), RescueOrderDetailsBean.class);
                        if (bean.isIsSuccess()) {
                            tvName.setText(bean.getData().getRescue());
                            tvCarNum.setText(bean.getData().getLicense_number());
                            if (Utils.isMobile(bean.getData().getCall_phone())) {
                                tel = bean.getData().getCall_phone();
                                StringBuilder sb = new StringBuilder(bean.getData().getCall_phone());
                                sb.replace(3, 7, "****");
                                tvPhoneNum.setText(sb);
                            }
                            tvPlace.setText(bean.getData().getRescue_address());
                            tvReason.setText(bean.getData().getRescue_result());
                            tvRoad.setText(bean.getData().getRoad_condition());
                            status = bean.getData().getStatus();
                            //未接单状态，自动获取员工列表
                            if (status == 0) {
                                getStaffList();
                            }
                            stateChange(bean.getData().getStatus(), bean.getData().getReceiving_order_time(), bean.getData().getArrival_time(), bean.getData().getOrder_completion_time());
                            Latitude = bean.getData().getLat();//获取纬度
                            Longitude = bean.getData().getLng();//获取经度
                            markerPosition = new LatLng(Latitude, Longitude);
                            mAMap.moveCamera(CameraUpdateFactory.changeLatLng(markerPosition));
                            addGrowMarker(markerPosition);
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接超时");
                        super.onError(response);
                    }
                });
    }

    private void stateChange(int status, String time, String time2, String time3) {
        if (status == 0) {
            llTime.setVisibility(View.GONE);
            tv1.setVisibility(View.VISIBLE);
            tv1.setText("未接单");
            tv1.setTextColor(Color.GRAY);
            tv2.setVisibility(View.INVISIBLE);
            tv3.setVisibility(View.INVISIBLE);
            btnComplete.setText("指派订单");
        } else if (status == 1) {
            llTime.setVisibility(View.VISIBLE);
            tv1.setVisibility(View.VISIBLE);
            tv2.setVisibility(View.INVISIBLE);
            tv3.setVisibility(View.INVISIBLE);
            tv1.setText("已接单");
            tv1.setTextColor(getResources().getColor(R.color.main_color));
            tvTime1.setVisibility(View.VISIBLE);
            tvTime2.setVisibility(View.INVISIBLE);
            tvTime3.setVisibility(View.INVISIBLE);
            tvTime1.setText(time);
            view1.setBackgroundColor(getResources().getColor(R.color.main_color));
            view2.setBackgroundColor(getResources().getColor(R.color.gray1));
            view3.setBackgroundColor(getResources().getColor(R.color.gray1));
            view4.setBackgroundColor(getResources().getColor(R.color.gray1));
            image1.setImageResource(R.mipmap.jiedan);
            image2.setImageResource(R.mipmap.gray);
            image3.setImageResource(R.mipmap.gray);
            btnComplete.setText("到达救援地点");
        } else if (status == 2) {
            llTime.setVisibility(View.VISIBLE);
            tv1.setVisibility(View.VISIBLE);
            tv2.setVisibility(View.VISIBLE);
            tv3.setVisibility(View.INVISIBLE);
            tv1.setText("已接单");
            tv2.setText("已到达");
            tv1.setTextColor(getResources().getColor(R.color.main_color));
            tv2.setTextColor(getResources().getColor(R.color.main_color));

            tvTime1.setVisibility(View.VISIBLE);
            tvTime2.setVisibility(View.VISIBLE);
            tvTime3.setVisibility(View.INVISIBLE);
            tvTime1.setText(time);
            tvTime2.setText(time2);

            view1.setBackgroundColor(getResources().getColor(R.color.main_color));
            view2.setBackgroundColor(getResources().getColor(R.color.main_color));
            view3.setBackgroundColor(getResources().getColor(R.color.gray1));
            view4.setBackgroundColor(getResources().getColor(R.color.gray1));
            image1.setImageResource(R.mipmap.jiedan);
            image2.setImageResource(R.mipmap.jiedan);
            image3.setImageResource(R.mipmap.gray);
            btnComplete.setText("救援信息上传");
        } else {
            llTime.setVisibility(View.VISIBLE);
            tv1.setVisibility(View.VISIBLE);
            tv2.setVisibility(View.VISIBLE);
            tv3.setVisibility(View.VISIBLE);
            tv1.setText("已接单");
            tv2.setText("已到达");
            tv3.setText("已完成");
            tv1.setTextColor(getResources().getColor(R.color.main_color));
            tv2.setTextColor(getResources().getColor(R.color.main_color));
            tv3.setTextColor(getResources().getColor(R.color.main_color));

            tvTime1.setVisibility(View.VISIBLE);
            tvTime2.setVisibility(View.VISIBLE);
            tvTime3.setVisibility(View.VISIBLE);
            tvTime1.setText(time);
            tvTime2.setText(time2);
            tvTime3.setText(time3);

            view1.setBackgroundColor(getResources().getColor(R.color.main_color));
            view2.setBackgroundColor(getResources().getColor(R.color.main_color));
            view3.setBackgroundColor(getResources().getColor(R.color.main_color));
            view4.setBackgroundColor(getResources().getColor(R.color.main_color));
            image1.setImageResource(R.mipmap.jiedan);
            image2.setImageResource(R.mipmap.jiedan);
            image3.setImageResource(R.mipmap.jiedan);
            btnComplete.setText("已完成");
        }
    }

    //获取员工信息
    private void getStaffList() {
        OkGo.<String>post(Config.s + "llc/api/RoadRescueController/selectStaff")
                .tag(this)
                .params("sid", shopID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SelectStaffBean bean = gson.fromJson(response.body(), SelectStaffBean.class);
                        if (bean.isIsSuccess()) {
                            mBeanList.clear();
                            mBeanList.addAll(bean.getData());
                            mStaffListAdapter.setNewData(mBeanList);
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接超时");
                        super.onError(response);
                    }
                });
    }

    //员工列表弹窗
    private void myDialog() {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_staff, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.setCanceledOnTouchOutside(false);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        TextView tv_cancle = bottomDialog.findViewById(R.id.tv_back);
        RecyclerView staff_recycleview=bottomDialog.findViewById(R.id.staff_recycleview);
        staff_recycleview.setNestedScrollingEnabled(false);
        staff_recycleview.setAdapter(mStaffListAdapter);
        mStaffListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selectStaffList(mBeanList.get(position).getUid(),mBeanList.get(position).getUsername(),mBeanList.get(position).getTel());
                bottomDialog.dismiss();
            }
        });
        staff_recycleview.setLayoutManager(new LinearLayoutManager(this));
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });


    }


    //选择员工
    private void selectStaffList(int id,String name, String phone) {
        OkGo.<String>post(Config.s + "llc/api/RoadRescueController/updateRescuerInformation")
                .tag(this)
                .params("uid", id)
                .params("username", name)
                .params("phone", phone)
                .params("id", shopID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SelectStaffBean1 bean = gson.fromJson(response.body(), SelectStaffBean1.class);
                        if (bean.isIsSuccess()) {
                            status=1;
                            stateChange(bean.getData().getStatus(),bean.getData().getReceiving_order_time(),"","");
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接超时");
                        super.onError(response);
                    }
                });
    }

    //到达救援地点弹窗
    private void arriveDialog() {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_arrive, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels-250;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.setCanceledOnTouchOutside(false);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        TextView tv_cancle = bottomDialog.findViewById(R.id.tv_cancel);
        TextView tv_Sure = bottomDialog.findViewById(R.id.tv_Sure);

        tv_Sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirmArrival();
                bottomDialog.dismiss();
            }
        });

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });

    }

    //确认到达救援现场
    private void confirmArrival() {
        OkGo.<String>post(Config.s + "llc/api/RoadRescueController/updateArrivalTime")
                .tag(this)
                .params("id", shopID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SelectStaffBean1 bean = gson.fromJson(response.body(), SelectStaffBean1.class);
                        if (bean.isIsSuccess()) {
                            status=2;
                            stateChange(bean.getData().getStatus(),bean.getData().getReceiving_order_time(),bean.getData().getArrival_time(),"");
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接超时");
                        super.onError(response);
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();

        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapview.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapview.onSaveInstanceState(outState);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.startAnimation();
        return true;
    }
}
